import axios, { InternalAxiosRequestConfig, AxiosResponse } from "axios";
import { useUserStoreHook } from "@/store/modules/user";
import { useStorage } from "@vueuse/core";

const accessToken = useStorage("accessToken", "");
const myrefreshToken = useStorage("myrefreshToken", "");
// 创建 axios 实例
const service = axios.create({
  baseURL: "",
  timeout: 50000,
  headers: { "Content-Type": "application/json;charset=utf-8" },
});

// 请求拦截器
service.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    const userStore = useUserStoreHook();
    if (userStore.token) {
      config.headers.Authorization = userStore.token;
      config.headers["X-Authorization"] = userStore.myrefreshToken;
    }
    return config;
  },
  (error: any) => {
    return Promise.reject(error);
  }
);

// 响应拦截器
service.interceptors.response.use(
  (response: AxiosResponse) => {
    const { status } = response;
    const { msg } = response.data;
    const tokenRes = response.headers["access-token"];
    const myrefreshTokenRes = response.headers["x-access-token"];

    if (tokenRes && myrefreshTokenRes) {
      accessToken.value = "Bearer" + " " + String(tokenRes);
      myrefreshToken.value = "Bearer" + " " + String(myrefreshTokenRes);
    }
    if (status === 200) {
      return response.data;
    }
    if (status === 401) {
      ElMessageBox.confirm("当前页面已失效，请重新登录", "提示", {
        confirmButtonText: "确定",
        type: "warning",
      }).then(() => {
        localStorage.clear();
        window.location.href = "/";
      });
    } else {
      ElMessage.error(msg || "系统出错");
      return Promise.reject(new Error(msg || "Error"));
    }

    // 响应数据为二进制流处理(Excel导出)
    if (response.data instanceof ArrayBuffer) {
      return response;
    }
  },
  (error: any) => {
    const { status } = error.response;
    if (status == 401) {
      ElMessageBox.confirm("当前页面已失效，请重新登录", "提示", {
        confirmButtonText: "确定",
        type: "warning",
      }).then(() => {
        localStorage.clear();
        window.location.href = "/";
      });
    } else {
      ElMessage.error("系统出错");
    }
  }
);
// 导出 axios 实例
export default service;
